<?php

namespace App\Http\Controllers\Api;

use App\Http\Requests\Api\DepartmentRequest;
use App\Models\Department;
use App\Transformers\DepartmentTransformer;
use Illuminate\Http\Request;

class DepartmentController extends Controller
{
    public function index(Request $request, Department $department)
    {
        $department = $department->newQuery();
        if ($request->input('name')) {
            $department->where('name', $request->input('name'));
        }
        if ($request->input('principal')) {
            $department->where('principal', $request->input('principal'));
        }
        if ($request->input('tel')) {
            $department->where('tel', $request->input('tel'));
        }
        $departments = $department->orderBy('created_at', 'desc')->paginate(20);

        return $this->response->paginator($departments, new DepartmentTransformer());
    }

    public function show(Department $department)
    {
        return $this->response->item($department, new DepartmentTransformer());
    }

    public function store(DepartmentRequest $request)
    {
        $check = Department::where('name', $request->input('name'))->first();
        if ($check) {
            return $this->response->error('部门已存在', 422);
        }
        $department = Department::create([
            'name' => $request->name,
            'principal' => $request->principal,
            'tel' => $request->tel,
            'tel_sub' => $request->tel_sub,
            'email' => $request->email,
        ]);

        return $this->response->item($department, new DepartmentTransformer())
            ->setStatusCode(201);
    }

    public function update(DepartmentRequest $request, Department $department)
    {
        if ($request->input('name') !== $department->name) {
            $check = Department::where('name', $request->input('name'))->first();
            if ($check) {
                return $this->response->error('部门已存在', 422);
            }
        }
        $department->update([
            'name' => $request->name,
            'principal' => $request->principal,
            'tel' => $request->tel,
            'tel_sub' => $request->tel_sub,
            'email' => $request->email,
        ]);

        return $this->response->item($department, new DepartmentTransformer());
    }

    public function delete(Department $department)
    {
        $department->delete();

        return $this->response->noContent();
    }
}
